package com.adee.gulimall.search.vo;

import co.elastic.clients.elasticsearch._types.SortOrder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class SearchParam4es extends SearchParam{
    private List<Attr> attrList;
    private Boolean hasStockBool;
    private Float skuPriceFrom;
    private Float skuPriceTo;
    private String sortField;
    private SortOrder sortOrder;
    private Integer from;
    private Integer size;

    public static SearchParam4es build(SearchParam p) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        SearchParam4es ps = new SearchParam4es();
        PropertyUtils.copyProperties(ps, p);
        // attrList
        List<String> attrs = ps.getAttrs();
        if(attrs != null) {
            List<Attr> list = ps.getAttrs().stream().map(s -> {
                String[] arr1 = s.split("_");
                long attrId = Long.parseLong(arr1[0]);
                String[] values = arr1[1].split(":");
                return new Attr(attrId, Arrays.asList(values));
            }).collect(Collectors.toList());
            ps.setAttrList(list);
        }

        // hasStockBool
        Integer hasStock = ps.getHasStock();
        if(hasStock != null) {
            ps.setHasStockBool(hasStock == 0 ? false : true);
        }

        // skuPrice
        String skuPrice = ps.getSkuPrice();
        if(skuPrice != null) {
            String[] priceArr = skuPrice.split("_");
            ps.setSkuPriceFrom("".equals(priceArr[0]) ? null : Float.parseFloat(priceArr[0]));
            ps.setSkuPriceTo("".equals(priceArr[1]) ? null : Float.parseFloat(priceArr[1]));
        }

        // sort
        String sort = ps.getSort();
        if(sort != null) {
            String[] arr = sort.split("_");
            ps.setSortField(arr[0]);
            ps.setSortOrder("desc".equals(arr[1]) ? SortOrder.Desc : SortOrder.Asc);
        }

        // page
        Integer pageNum = ps.getPageNum();
        if(pageNum != null) {
            ps.setFrom((pageNum-1)*10);
            ps.setSize(10);
        }

        return ps;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Attr {
        private Long attrId;
        private List<String> attrValues;
    }
}
